<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 顶部导航栏 -->
    <header class="sticky top-0 z-50 bg-white shadow-md transition-all duration-300">
      <div class="container mx-auto px-4">
        <div class="flex items-center justify-between h-16 md:h-20">
          <!-- Logo -->
          <div class="flex items-center">
            <router-link to="/" class="flex items-center">
              <i class="fas fa-book text-primary text-2xl md:text-3xl mr-2"></i>
              <span class="text-xl md:text-2xl font-bold text-primary" style="font-weight: 700;">书香阁</span>
            </router-link>
          </div>

          <!-- 主导航 - 桌面版 -->
          <nav class="hidden md:flex items-center space-x-8">
            <router-link to="/home" class="font-medium text-gray-600 hover:text-primary transition-colors py-1">首页</router-link>
            <router-link to="/category" class="font-medium text-gray-600 hover:text-primary transition-colors py-1">分类</router-link>
            <router-link to="/bestseller" class="font-medium text-primary border-b-2 border-primary py-1">畅销榜</router-link>
            <router-link to="/news" class="font-medium text-gray-600 hover:text-primary transition-colors py-1">资讯</router-link>
          </nav>

          <!-- 搜索框 -->
          <div class="hidden md:flex items-center flex-1 max-w-md mx-8">
            <div class="relative w-full flex">
              <el-input
                v-model="searchKeyword"
                placeholder="请输入您喜欢的商品"
                class="search-input flex-1"
                @keyup.enter="handleSearch"
              >
                <template #prefix>
                  <i class="fas fa-search text-gray-400"></i>
                </template>
              </el-input>
              <button
                @click="handleSearch"
                class="search-button ml-2 px-4 py-2 text-white rounded-full transition-colors flex items-center justify-center"
              >
                <i class="fas fa-search"></i>
              </button>
            </div>
          </div>

          <!-- 用户工具栏 -->
          <div class="flex items-center space-x-4">
            <button class="relative p-2 text-gray-600 hover:text-primary transition-colors">
              <i class="fas fa-bell text-lg"></i>
              <span class="absolute top-1 right-1 w-2 h-2 bg-red-500 rounded-full"></span>
            </button>
            <button
              @click="goToCart"
              class="relative p-2 text-gray-600 hover:text-primary transition-colors"
            >
              <i class="fas fa-shopping-cart text-lg"></i>
              <span
                class="absolute text-white text-xs rounded-full w-5 h-5 flex items-center justify-center"
                style="top: -4px; right: -4px; z-index: 100; min-width: 20px; font-weight: bold; background-color: #FF6B8A;"
              >{{ cartCount || 0 }}</span>
            </button>

            <!-- 用户下拉菜单 -->
            <el-dropdown @command="handleCommand">
              <span class="el-dropdown-link cursor-pointer flex items-center">
                <el-avatar :size="32" :src="getImageUrl(userStore.userInfo?.avatar)">
                  <i class="fas fa-user"></i>
                </el-avatar>
                <span class="hidden md:block ml-2 text-gray-600">{{ userStore.userInfo?.username }}</span>
                <i class="fas fa-chevron-down ml-1 text-gray-400"></i>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="profile">个人资料</el-dropdown-item>
                  <el-dropdown-item command="orders">我的订单</el-dropdown-item>
                  <el-dropdown-item command="settings">设置</el-dropdown-item>
                  <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>

            <!-- 移动端菜单按钮 -->
            <button @click="toggleMobileMenu" class="md:hidden p-2 text-gray-600 hover:text-primary transition-colors">
              <i class="fas fa-bars text-xl"></i>
            </button>
          </div>
        </div>

        <!-- 移动端搜索框 -->
        <div class="md:hidden pb-4">
          <div class="flex">
            <el-input
              v-model="searchKeyword"
              placeholder="请输入您喜欢的商品"
              class="search-input flex-1"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <i class="fas fa-search text-gray-400"></i>
              </template>
            </el-input>
            <button
              @click="handleSearch"
              class="search-button ml-2 px-4 py-2 text-white rounded-full transition-colors flex items-center justify-center"
            >
              <i class="fas fa-search"></i>
            </button>
          </div>
        </div>
      </div>

      <!-- 移动端导航菜单 -->
      <div v-show="showMobileMenu" class="md:hidden bg-white border-t border-gray-100 shadow-lg">
        <div class="container mx-auto px-4 py-3 space-y-3">
          <router-link to="/home" class="block py-2 px-3 rounded-lg hover:bg-gray-100 transition-colors">首页</router-link>
          <router-link to="/category" class="block py-2 px-3 rounded-lg hover:bg-gray-100 transition-colors">分类</router-link>
          <router-link to="/bestseller" class="block py-2 px-3 rounded-lg bg-primary/10 text-primary font-medium">畅销榜</router-link>
          <router-link to="/news" class="block py-2 px-3 rounded-lg hover:bg-gray-100 transition-colors">资讯</router-link>
        </div>
      </div>
    </header>

    <!-- 主要内容 -->
    <main class="container mx-auto px-4 py-6">
      <!-- 页面标题 -->
      <section class="mb-8">
        <div class="text-center">
          <h1 class="text-3xl md:text-4xl font-bold text-gray-800 mb-4">
            <i class="fas fa-trophy text-primary mr-3"></i>
            畅销图书排行榜
          </h1>
          <p class="text-gray-600 text-lg max-w-2xl mx-auto">
            基于真实销售数据统计，为您推荐最受读者喜爱的优质图书
          </p>
        </div>
      </section>

      <!-- 分类标签 -->
      <section class="mb-8">
        <div class="flex flex-wrap justify-center gap-4">
          <button
            v-for="category in categories"
            :key="category.id"
            @click="switchCategory(category.id)"
            :class="[
              'px-6 py-3 rounded-full font-medium transition-all duration-300',
              activeCategory === category.id
                ? 'active-category-btn text-white shadow-lg'
                : 'inactive-category-btn text-gray-600 hover:text-primary border border-gray-200'
            ]"
          >
            {{ category.name }}
          </button>
        </div>
      </section>

      <!-- 畅销榜列表 -->
      <section class="mb-16">
        <div class="bg-white rounded-2xl shadow-sm overflow-hidden">
          <div class="p-6 border-b border-gray-100">
            <h2 class="text-xl font-bold text-gray-800 flex items-center">
              <i class="fas fa-chart-line text-primary mr-2"></i>
              {{ getCurrentCategoryName() }}畅销榜
            </h2>
          </div>
          
          <div class="divide-y divide-gray-100">
            <div
              v-for="(book, index) in getCurrentBooks()"
              :key="book.id"
              @click="goToBookDetail(book.book?.id)"
              class="p-6 hover:bg-gray-50 transition-colors cursor-pointer flex items-center space-x-6"
            >
              <!-- 排名 -->
              <div class="flex-shrink-0">
                <div
                  :class="[
                    'w-12 h-12 rounded-full flex items-center justify-center font-bold text-lg',
                    index < 3 ? 'bg-gradient-to-r from-yellow-400 to-yellow-600 text-white' : 'bg-gray-100 text-gray-600'
                  ]"
                >
                  {{ index + 1 }}
                </div>
              </div>

              <!-- 图书封面 -->
              <div class="flex-shrink-0">
                <img
                  :src="getImageUrl(book.book?.cover)"
                  :alt="book.book?.title"
                  class="w-20 h-28 object-cover rounded-lg shadow-sm"
                  @error="handleImageError"
                >
              </div>

              <!-- 图书信息 -->
              <div class="flex-1 min-w-0">
                <h3 class="text-lg font-bold text-gray-800 mb-2 line-clamp-1">{{ book.book?.title }}</h3>
                <p class="text-gray-600 mb-2">作者：{{ book.book?.author }}</p>
                <p class="text-gray-500 text-sm mb-3 line-clamp-2">{{ book.book?.description }}</p>
                <div class="flex items-center space-x-4 mb-2">
                  <span class="text-primary font-bold text-xl">¥{{ book.book?.price }}</span>
                  <span class="text-gray-400 text-sm">{{ book.book?.publisher }}</span>
                  <div class="flex items-center text-yellow-500">
                    <i class="fas fa-star mr-1"></i>
                    <span class="text-gray-600">{{ book.book?.rating || '0.0' }}</span>
                  </div>
                </div>
                <!-- 显示分类信息（仅在综合榜中显示） -->
                <div v-if="activeCategory === 0" class="flex items-center">
                  <span class="inline-block px-2 py-1 bg-blue-100 text-blue-800 text-xs rounded-full">
                    {{ getCategoryName(book.book?.categoryId) }}
                  </span>
                </div>
              </div>

              <!-- 销量信息 -->
              <div class="flex-shrink-0 text-right">
                <div class="text-primary font-bold text-lg mb-1">{{ book.book?.sales || 0 }}</div>
                <div class="text-gray-500 text-sm">本月销量</div>
                <div class="mt-3 flex justify-end">
                  <button
                    @click.stop="addToCart(book.book)"
                    class="w-10 h-10 add-to-cart-btn text-white rounded-full transition-colors flex items-center justify-center"
                    title="加入购物车"
                  >
                    <i class="fas fa-shopping-cart"></i>
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>
    </main>

    <!-- 底部页脚 -->
    <footer class="bg-gray-900 text-white py-10">
      <div class="container mx-auto px-4">
        <div class="grid grid-cols-1 md:grid-cols-4 gap-8">
          <!-- 关于我们 -->
          <div>
            <h3 class="text-lg font-bold mb-4 text-primary">关于书香阁</h3>
            <p class="text-gray-400 text-sm">
              书香阁是专业的网上书店，提供超过10万种图书在线购买，支持快递配送和自提服务，让阅读触手可及。
            </p>
            <div class="flex space-x-4 mt-4">
              <a href="#" class="text-gray-400 hover:text-primary"><i class="fab fa-weixin text-xl"></i></a>
              <a href="#" class="text-gray-400 hover:text-primary"><i class="fab fa-weibo text-xl"></i></a>
              <a href="#" class="text-gray-400 hover:text-primary"><i class="fab fa-qq text-xl"></i></a>
              <a href="#" class="text-gray-400 hover:text-primary"><i class="fas fa-envelope text-xl"></i></a>
            </div>
          </div>

          <!-- 快捷链接 -->
          <div>
            <h3 class="text-lg font-bold mb-4 text-primary">快捷链接</h3>
            <ul class="space-y-2 text-sm">
              <li><router-link to="/category" class="text-gray-400 hover:text-primary">分类浏览</router-link></li>
              <li><router-link to="/bestseller" class="text-gray-400 hover:text-primary">热门排行</router-link></li>
              <li><a href="#" class="text-gray-400 hover:text-primary">最新上架</a></li>
              <li><a href="#" class="text-gray-400 hover:text-primary">特价促销</a></li>
              <li><a href="#" class="text-gray-400 hover:text-primary">读者推荐</a></li>
            </ul>
          </div>

          <!-- 客户服务 -->
          <div>
            <h3 class="text-lg font-bold mb-4 text-primary">客户服务</h3>
            <ul class="space-y-2 text-sm">
              <li><a href="#" class="text-gray-400 hover:text-primary">常见问题</a></li>
              <li><a href="#" class="text-gray-400 hover:text-primary">配送方式</a></li>
              <li><a href="#" class="text-gray-400 hover:text-primary">支付方式</a></li>
              <li><a href="#" class="text-gray-400 hover:text-primary">退换政策</a></li>
              <li><a href="#" class="text-gray-400 hover:text-primary">联系我们</a></li>
            </ul>
          </div>

          <!-- 联系方式 -->
          <div>
            <h3 class="text-lg font-bold mb-4 text-primary">联系我们</h3>
            <ul class="space-y-3 text-sm">
              <li class="flex items-start">
                <i class="fas fa-map-marker-alt text-primary mt-1 mr-3"></i>
                <span class="text-gray-400">北京市朝阳区建国路88号</span>
              </li>
              <li class="flex items-center">
                <i class="fas fa-phone text-primary mr-3"></i>
                <span class="text-gray-400">400-800-1234</span>
              </li>
              <li class="flex items-center">
                <i class="fas fa-envelope text-primary mr-3"></i>
                <span class="text-gray-400">service@bookstore.com</span>
              </li>
              <li class="flex items-center">
                <i class="fas fa-clock text-primary mr-3"></i>
                <span class="text-gray-400">周一至周日 9:00-22:00</span>
              </li>
            </ul>
          </div>
        </div>

        <!-- 版权信息 -->
        <div class="border-t border-gray-800 mt-8 pt-8 flex flex-col md:flex-row justify-between items-center">
          <div class="text-gray-500 text-sm mb-4 md:mb-0">
            © {{ new Date().getFullYear() }} 书香阁 版权所有 | 京ICP备12345678号
          </div>
          <div class="flex space-x-4">
            <a href="#" class="text-gray-500 text-sm hover:text-primary">隐私政策</a>
            <a href="#" class="text-gray-500 text-sm hover:text-primary">使用条款</a>
            <a href="#" class="text-gray-500 text-sm hover:text-primary">网站地图</a>
          </div>
        </div>
      </div>
    </footer>

    <!-- 回到顶部按钮 -->
    <BackToTop />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { useCartStore } from '@/stores/cart'
import { ElMessage } from 'element-plus'
import { bookAPI } from '@/api/book'
import ggbondImg from '@/assets/images/ggbond.png'
import BackToTop from '@/components/BackToTop.vue'

const router = useRouter()
const userStore = useUserStore()
const cartStore = useCartStore()

// 响应式数据
const searchKeyword = ref('')
const showMobileMenu = ref(false)
const activeCategory = ref(0) // 0表示全部
const loading = ref(false)
const bestsellerList = ref([])
const pagination = reactive({
  current: 1,
  size: 20,
  total: 0
})

// 计算购物车数量，使用cartStore
const cartCount = computed(() => cartStore.cartCount)

// 分类数据
const categories = reactive([
  { id: 0, name: '全部' },
  { id: 1, name: '外语学习' },
  { id: 2, name: '文学小说' },
  { id: 3, name: '经管励志' },
  { id: 4, name: '科技教育' },
  { id: 5, name: '人文社科' },
  { id: 6, name: '少儿读物' }
])

// 加载畅销榜单数据
const loadBestsellerList = async () => {
  loading.value = true
  try {
    const params = {
      current: pagination.current,
      size: pagination.size,
      categoryId: activeCategory.value === 0 ? null : activeCategory.value,
      period: 'monthly'
    }

    const response = await bookAPI.getBestsellerList(params)

    if (response.code === 200) {
      bestsellerList.value = response.data.records || []
      pagination.total = response.data.total || 0
    } else {
      ElMessage.error(response.message || '获取畅销榜单失败')
    }
  } catch (error) {
    console.error('获取畅销榜单失败:', error)
    ElMessage.error('获取畅销榜单失败')
  } finally {
    loading.value = false
  }
}
// 切换分类时重新加载数据
const switchCategory = (categoryId) => {
  activeCategory.value = categoryId
  pagination.current = 1
  loadBestsellerList()
}

// 方法
const toggleMobileMenu = () => {
  showMobileMenu.value = !showMobileMenu.value
}

const handleSearch = () => {
  if (searchKeyword.value.trim()) {
    ElMessage.info(`搜索功能开发中，搜索关键词：${searchKeyword.value}`)
  }
}

const getCurrentCategoryName = () => {
  const category = categories.find(c => c.id === activeCategory.value)
  return category ? category.name : '全部'
}

const getCategoryName = (categoryId) => {
  const category = categories.find(c => c.id === categoryId)
  return category ? category.name : '未知分类'
}

const getCurrentBooks = () => {
  return bestsellerList.value || []
}

const goToBookDetail = (bookId) => {
  router.push(`/book/${bookId}`)
}

// 添加到购物车方法修改
const addToCart = async (book) => {
  try {
    await cartStore.addToCart(book)
    // 消息提示已在store中处理，这里不需要重复提示
  } catch (error) {
    console.error('添加到购物车失败:', error)
  }
}

const goToCart = () => {
  router.push('/cart')
}

// 处理下拉菜单命令
const handleCommand = (command) => {
  switch (command) {
    case 'profile':
      router.push('/profile')
      break
    case 'orders':
      router.push('/orders')
      break
    case 'settings':
      router.push('/settings')
      break
    case 'logout':
      handleLogout()
      break
  }
}

// 处理登出
const handleLogout = () => {
  userStore.logout()
  ElMessage.success('已退出登录')
  router.push('/login')
}

// 获取图片URL
const getImageUrl = (url) => {
  if (!url) return ''

  // 如果是完整的URL，直接返回
  if (url.startsWith('http')) {
    return url
  }

  // 如果是上传的文件路径
  if (url.startsWith('/uploads/')) {
    return `http://localhost:8081/api${url}`
  }

  // 如果是静态资源路径
  if (url.startsWith('/assets/')) {
    return `http://localhost:8081/api${url}`
  }

  // 其他情况，返回默认图片
  return ggbondImg
}

// 处理图片加载错误
const handleImageError = (event) => {
  event.target.src = ggbondImg
}

// 生命周期
onMounted(() => {
  loadBestsellerList()
})
</script>

<style scoped>
/* 自定义样式 */
:root {
  --primary: #FF6B8A;
  --primary-light: #FFB3C6;
  --primary-dark: #E55A7A;
  --secondary: #FFF0F3;
  --accent: #FF8FA3;
  --success: #4CAF50;
  --warning: #FF9800;
  --info: #2196F3;
  --dark: #2D3748;
  --gray: #718096;
  --light-gray: #F7FAFC;
  --white: #FFFFFF;
}

/* 购物车徽章样式 */
.cart-badge {
  z-index: 50 !important;
  transform: translate(25%, -25%) !important;
  min-width: 20px !important;
  height: 20px !important;
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
  font-size: 12px !important;
  font-weight: bold !important;
}

.el-dropdown-link {
  display: flex;
  align-items: center;
  color: #606266;
  transition: color 0.3s ease;
}

.el-dropdown-link:hover {
  color: var(--primary);
}

/* 搜索框样式 */
.search-input :deep(.el-input__wrapper) {
  border-radius: 9999px;
  border: 1px solid #d1d5db;
  transition: all 0.3s ease;
}

.search-input :deep(.el-input__wrapper):hover {
  border-color: var(--primary);
}

.search-input :deep(.el-input__wrapper.is-focus) {
  border-color: var(--primary);
  box-shadow: 0 0 0 2px rgba(255, 107, 139, 0.2);
}

/* 搜索按钮样式 */
.search-button {
  background-color: #FF6B8B !important;
}

.search-button:hover {
  background-color: rgba(255, 107, 139, 0.8) !important;
}

/* 文本截断 */
.line-clamp-1 {
  display: -webkit-box;
  -webkit-line-clamp: 1;
  line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 主题色定义 */
.text-primary {
  color: rgb(255, 107, 139);
}

.bg-primary {
  background-color: var(--primary);
}

.border-primary {
  border-color: var(--primary);
}

.bg-primary-dark {
  background-color: var(--primary-dark);
}

.hover\:bg-primary-dark:hover {
  background-color: var(--primary-dark);
}

/* 分类按钮样式 */
.active-category-btn {
  background-color: #FF6B8B !important;
}

.inactive-category-btn {
  background-color: white;
}

.inactive-category-btn:hover {
  background-color: rgba(255, 107, 139, 0.1) !important;
}

/* 加入购物车按钮样式 */
.add-to-cart-btn {
  background-color: #FF6B8B !important;
  box-shadow: 0 2px 4px rgba(255, 107, 139, 0.2);
}

.add-to-cart-btn:hover {
  background-color: #E55A7A !important;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(255, 107, 139, 0.3);
}
</style>
